<script setup lang="ts">
import { reactive, ref } from "vue";
import Vcode from "vue3-puzzle-vcode";
import type { FormInstance, FormRules } from "element-plus";
import { login } from "@/api/user-app";
import router from "@/router";
import { useAppStoreWithOut } from "@/store/modules/app";
import { saveStorage } from "@/utils/storage/storage";
import { encrypt } from "@/utils/index"
interface userForm {
  userName: string;
  passWord: string;
  code: string;
}
const store = useAppStoreWithOut()
const ruleFormRef = ref<FormInstance>();
const isShow = ref(false);
const Vcodevalidate = ref(false);
const onSuccess = () => {
  isShow.value = false;
  Vcodevalidate.value = true;
  submit()
};
const onClose = () => {};
const onFail = () => {};

const ruleForm = reactive<userForm>({
  userName: "",
  passWord: "",
  code: "",
});
const rules = reactive<FormRules<userForm>>({
  userName: [{ required: true, message: "请输入您的用户名", trigger: "blur" }],
  passWord: [{ required: true, message: "请输入您的密码", trigger: "blur" }],
});
const submit = async () => {
  const valid = await ruleFormRef.value.validate();
  if (!valid) return;
  if (!Vcodevalidate.value){
    isShow.value = true;
    return 
  }
 try {
  const s = encrypt(ruleForm.passWord)
  if (!s) return
  const res =  await login<{token:string}>({
    username: ruleForm.userName,
    passWord: s,
  })
  store.setToken(res.token)
  router.push('/')
  saveStorage('token',res.token)
  
 } catch (error) {
  
 }

};
</script>
<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    size="default"
    status-icon
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="ruleForm.userName">
        <template #prefix>
          <el-icon class="el-input__icon">
            <FontIcon iconKey="User"></FontIcon>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="密码" prop="passWord" @change="()=>Vcodevalidate = false">
      <el-input v-model="ruleForm.passWord" show-password type="password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <FontIcon iconKey="Lock"></FontIcon>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <div style="width: 100%" class="flex">
        <el-button type="primary" style="width: 90%" @click="submit"
          >登 陆</el-button
        >
      </div>
    </el-form-item>
  </el-form>
  <Vcode
    :show="isShow"
    @success="onSuccess"
    @close="onClose"
    @fail="onFail"
  ></Vcode>
</template>
<style scoped lang="sass"></style>
